package com.foreknow.dao.impl;

import com.foreknow.dao.AdminDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Admin;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl extends BaseDAO implements AdminDao {

    @Override
    public boolean register(Admin admin) throws SQLException {
        String sql = "insert into admin (username,password) values(?,?)";
        int update=1;
        boolean IsRight=false;
        update = jdbcTemplate.update(sql, admin.getUsername(), admin.getPassword());
        if (update != 0) {
            return true;
        }
        return IsRight;
    }

    @Override
    public Admin login(Admin admin)throws SQLException{
        String sql = "select username,password from Admin";
        EntityMapping map = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query(sql, map);
        for (int i = 0; i < list.size(); i++) {
            Admin DataBaseAdmin = (Admin) list.get(i);
            String username = admin.getUsername();
            String password = admin.getPassword();
            if (username.equals(DataBaseAdmin.getUsername()) && password.equals(DataBaseAdmin.getPassword())) {
                return DataBaseAdmin;
            }
        }
        return null;
    }

    /*public static void main(String[] args) {
        DBManager instance = DBManager.getInstance();
        Connection conn = instance.getConnection();
        JdbcTemplate instance1 = JdbcTemplate.getInstance();
        instance1.setConnection(conn);
        AdminDaoImpl ad=new AdminDaoImpl();
        Admin admin=new Admin();
        admin.setUsername("tom");
        admin.setPassword("123");
        boolean login = ad.login(admin);
        if (login) {
            System.out.println("登录成功！");
        }
    }*/
}
